<?php
/**
 * Created by PhpStorm.
 * User: Admin
 * Date: 2019/1/16
 * Time: 17:24
 */

namespace App\Http\Controllers;

use Dingo\Api\Routing\Helpers;
use Dingo\Api\Exception\ValidationHttpException;
use Illuminate\Support\Facades\Validator;

class BaseController extends Controller
{
    use Helpers;

    /**
     * Handle the bad request
     *
     * @param $validator
     */
    protected function errorBadRequest($validator)
    {
        $result = [];
        /* @var $validator \Illuminate\Validation\Validator */
        $messages = $validator->errors()->toArray();
        if ($messages) {
            foreach ($messages as $field => $errors) {
                foreach ($errors as $error) {
                    $result[] = [
                        'field' => $field,
                        'code' => $error,
                    ];
                }
            }
        }
        throw new ValidationHttpException($result);
    }

    /**
     * @param \Illuminate\Http\Request $request
     * @param array $rules
     */
    public function validateField($request, array $rules = [])
    {
        $validator = Validator::make($request->input(), $rules);
        if ($validator->fails()) {
            return $this->errorBadRequest($validator);
        }
    }
}
